from django.db import models
from django.conf import settings
from apps.product.models import Product, SKU

class CartItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='商品')
    sku = models.ForeignKey(SKU, on_delete=models.CASCADE, verbose_name='商品规格', null=True)
    quantity = models.IntegerField(default=1, verbose_name='数量')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '购物车项'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user', 'product', 'sku']),
        ]

    def __str__(self):
        sku_name = f"({self.sku.name})" if self.sku else ""
        return f'{self.user.username} - {self.product.name}{sku_name} x {self.quantity}'

    def save(self, *args, **kwargs):
        # 检查是否已存在相同的商品和规格
        if not self.pk:  # 只在创建新记录时检查
            existing = CartItem.objects.filter(
                user=self.user,
                product=self.product,
                sku=self.sku
            ).first()
            if existing:
                existing.quantity += self.quantity
                existing.save()
                return existing
        return super().save(*args, **kwargs)
